﻿create proc sp_MergeProject
AS
MERGE Project AS Target
USING 
(
	SELECT DISTINCT 
		ProgramId
		, ProjectName
		, ProjectId
	FROM ProjectProgramTemp
	WHERE ProjectId IS NOT NULL AND ProjectId <> ''
) AS Source
ON
(
	Target.Id = Source.ProjectId 
)
WHEN MATCHED THEN
	UPDATE SET 
		ProjectName = Source.ProjectName
		, ProgramId = Source.ProgramId
WHEN NOT MATCHED BY Target THEN
	INSERT 
	(
		Id
		, ProjectName
		, ProgramId
	) 
	Values
	(
		Source.ProjectId
		, Source.ProjectName
		, Source.ProgramId
	);